<?php

require_once 'Base.php';

class Certificates extends Base {

    /**
     * 获取平台证书
     * 若key存在则获取证书对应的key
     */
    public function get($key=''){
        if(file_exists($this->certDataPath)){
            $cert=json_decode(file_get_contents($this->certDataPath), true);
        }else{
            $cert=$this->apply();
        }
        return $key?$cert['data'][0][$key]:$cert;
    }

    //申请平台证书
    public function apply(){
        $requestParams=[
            'mch_id'=>$this->mch_id,
            'nonce_str'=>md5(time()),
            'sign_type'=>'HMAC-SHA256'
        ];
        $requestParams['sign']=$this->generateSign($requestParams);
        $url='https://api.mch.weixin.qq.com/risk/getcertficates';

        $response=$this->curlRequest($url,$this->arrayToXml($requestParams));

        if($response['return_code']=='SUCCESS'){
            if($response['result_code']=='SUCCESS'){
                file_put_contents($this->certDataPath,$response['certificates']);
                $certificates=json_decode($response['certificates'],true);
                $this->decryptCiphertext($certificates['data'][0]);
                return json_decode($response['certificates'],true);
            }
            exit($response['err_code_desc']);
        }
        exit($response['return_msg']);
    }

    //AEAD_AES_256_GCM 解密加密后的证书内容得到平台证书的明文
    public function decryptCiphertext($data){
        $encryptCertificate = $data['encrypt_certificate'];
        $ciphertext         = base64_decode($encryptCertificate['ciphertext']);
        $associated_data    = $encryptCertificate['associated_data'];
        $nonce              = $encryptCertificate['nonce'];
        // sodium_crypto_aead_aes256gcm_decrypt >=7.2版本，去php.ini里面开启下libsodium扩展就可以，之前版本需要安装libsodium扩展，具体查看php.net（ps.使用这个函数对扩展的版本也有要求哦，扩展版本 >=1.08）
        // 安装教程http://www.php.cn/topic/php7/418425.html
        $check_sodium_mod = extension_loaded('sodium');
        if ($check_sodium_mod === false) {
            exit('没有安装sodium模块');
        }
        $check_aes256gcm = sodium_crypto_aead_aes256gcm_is_available();
        if ($check_aes256gcm === false) {
            exit('当前不支持aes256gcm');
        }
        //平台证书明文
        $plaintext = sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associated_data, $nonce, $this->aes_key);
        file_put_contents($this->publicKeyPath, $plaintext);
        return true;
    }
}